# ========= 应用基本信息 =========
APP_NAME := stock-plus
ENTRY := ./cmd/cli/main.go
OUTPUT_DIR := bin
CONFIG_FILE := configs

IMAGE_NAME := registry.cn-shenzhen.aliyuncs.com/lyuanbo/stock-plus

# ========= 构建元信息 =========
VERSION := v$(shell gitversion /showvariable FullSemVer)
GIT_COMMIT := $(shell git rev-parse --short HEAD)
BUILD_TIME := $(shell TZ=Asia/Shanghai date "+%Y-%m-%d %H:%M:%S")

# ========= 构建平台配置 =========
GOOS ?= $(shell go env GOOS)
GOARCH ?= $(shell go env GOARCH)

# ========= 构建输出路径 =========
OUTPUT_FILE := $(OUTPUT_DIR)/$(APP_NAME)_$(GOOS)_$(GOARCH)$(if $(findstring windows,$(GOOS)),.exe)
LDFLAGS := -X gitee.com/lyuanbo/stock-plus/pkg/version.Version=$(VERSION) \
           -X gitee.com/lyuanbo/stock-plus/pkg/version.Commit=$(GIT_COMMIT) \
           -X gitee.com/lyuanbo/stock-plus/pkg/version.BuildTime=$(BUILD_TIME)

.PHONY: all build clean linux windows mac deps docker-build wire tls tag

all: build

deps:
	@echo "==> Installing dependencies..."

build:
	@echo "==> Building for $(GOOS)/$(GOARCH)..."
	@mkdir -p $(OUTPUT_DIR)
	@echo "==> Output file: $(OUTPUT_FILE)"
	GOOS=$(GOOS) GOARCH=$(GOARCH) CGO_ENABLED=0 go build -ldflags="$(LDFLAGS)" -o $(OUTPUT_FILE) $(ENTRY)

clean:
	@echo "==> Cleaning..."
	@rm -rf $(OUTPUT_DIR)

linux:
	@GOOS=linux GOARCH=amd64 $(MAKE) all

windows:
	@GOOS=windows GOARCH=amd64 $(MAKE) all

mac:
	@GOOS=darwin GOARCH=arm64 $(MAKE) all

tag:
	@echo "==> Tagging..."
	@git tag -a $(VERSION) -m "release $(VERSION)"

docker-build:
	@echo "==> Pulling latest code..."
	@git pull origin $$(git rev-parse --abbrev-ref HEAD)

    # 上面重新拉取代码，为了获取最新版本的 gitversion
	@echo "==> Getting version info..."
	$(eval VERSION := v$(shell gitversion /showvariable FullSemVer))
	$(eval GIT_COMMIT := $(shell git rev-parse --short HEAD))
	$(eval BUILD_TIME := $(shell TZ=Asia/Shanghai date "+%Y-%m-%d %H:%M:%S"))

	@echo "==> Building Docker image: $(IMAGE_NAME):$(VERSION)"
	docker login -u qq1214576607 -p 'hzTU5fzXa5MY_-s' registry.cn-shenzhen.aliyuncs.com
	docker buildx build \
		--build-arg VERSION=$(VERSION) \
		--build-arg COMMIT=$(GIT_COMMIT) \
		--build-arg BUILD_TIME="$(BUILD_TIME)" \
		--cache-from=type=local,src=.buildx-cache \
        --cache-to=type=local,dest=.buildx-cache \
		-f ./deploy/Dockerfile \
		-t $(IMAGE_NAME):$(VERSION) \
		--push \
		--progress=plain \
		.

	@echo "==> 判断是否在 master 分支"
	@if [ "$$(git rev-parse --abbrev-ref HEAD)" = "master" ]; then \
		echo "==> 当前在 master, 创建并推送 Git Tag: $(VERSION)"; \
		git tag -a $(VERSION) -m "release $(VERSION)"; \
		git push origin $(VERSION); \
	else \
		echo "==> 当前不在 master, 跳过打 tag"; \
	fi

wire:
	cd ./internal/di && wire .
